For loop
for loop在python中的語法為:for item in sequence
sequence為要迴圈的序列,item為序列中的元素,for迴圈會將序列中的元素依序取出,然而在Python中序列類型的物件有list、tuple、range、其中string也可以放進迴圈裡
#%% For loop
nums = [1,2,3,4,5]
for num in nums:
if num == 3:
print('Found!')
# break
continue
print(num)
double for loop
#%% Double for loop
for num in nums:
for letter in 'abc':
print(num, letter)
內建函式 Built-in function: range()
range函式語法為: range(start, stop[, step])
#%% built-in function: range()
for i in range(1,10):
print(i)
While loop
#%% while loop
x = 0
while x < 10:
if x == 5:
break
print(x)
x += 1
#%% Infinity loop: with interruption key "Ctrl+C"
x = 10
while True:
print(x)
x += 1
之後還會介紹用break/ continue的流程控制語法來控制loop迴圈